<?php
namespace app\index\controller;

use think\Controller;
use think\Session;
use think\Db;

class District extends Controller
{
	/**
	 * 分区列表
	 * @author 秋水
	 * @DateTime 2019-02-14T13:50:13+0800
	 */
	public function index()
	{
        $code = session('code','');
        
        $where = 'is_del=1';

        $count = db('district')->where($where)->count();

        $list = db('district')->alias('a')->join('ap_user b','a.user_id=b.id','left')->field('a.*,b.username')->where($where)->order('id asc')->paginate(10, false, [
            'query' => input()
        ]);

        return view('index',[
            'count'=> $count,
            'list'  =>  $list,
            'code'  =>  $code
        ]);
	}

	/**
	 * 添加分区
	 * @author 秋水
	 * @DateTime 2019-02-14T14:30:22+0800
	 */
	public function add()
	{
		if(request()->isPost()) {
			$name = input('name', '');
			$number = input('number', 0);
			$status = input('status', 1);

			if($number == 0) {
				$maxNumber = db('district')->field('max(number) as max_number')->where(['is_del'=>1,'status'=>1])->find();
				$number = $maxNumber+1;
			}

			$addData = [
				'name' => $name,
				'number' => $number,
				'is_del' => 1,
				'status' => $status
			];

			$r = db('district')->insert($addData);
			if($r) {
				Session::flash('code','1');
                $this->redirect('district/index');
            }else{
                Session::flash('code','err2');
                $this->redirect('district/add' );
            };
		} else {
			$maxNumber = db('district')->field('max(number) as max_number')->where(['is_del'=>1,'status'=>1])->find();

			$this->assign('max_number',$maxNumber['max_number']);
			return view('add');
		}
	}

	/**
	 * 修改分区信息
	 * @author 秋水
	 * @DateTime 2019-02-14T15:13:43+0800
	 */
	public function edit()
	{
		if(request()->isPost()) {
			$id = input('id',0);
			$name = input('name', '');
			$number = input('number', 0);
			$status = input('status', 1);

			$updateData = [
				'name' => $name,
				'number' => $number,
				'status' => $status
			];

			$r = db('district')->where('id',$id)->update($updateData);
			if($r) {
				Session::flash('code','1');
                $this->redirect('district/index');
            }else{
                Session::flash('code','err2');
                $this->redirect('district/edit' );
            };
		} else {
			$id = input('id', 0);
			$data = db('district')->where('id',$id)->find();

			$this->assign('data',$data);
			return view('edit');
		}
	}

	/**
	 * 删除分区
	 * @author 秋水
	 * @DateTime 2019-02-14T15:20:33+0800
	 */
	public function delete()
	{
		$id = input('id', 0);

		$r = db('district')->where('id',$id)->update(['is_del'=>0]);

		if($r) {
			return json(['code'=>1,'msg'=>'删除成功']);
		} else {
			return json(['code'=>0,'msg'=>'删除失败']);
		}
	}

	/**
	 * 分区申请列表
	 * @author 秋水
	 * @DateTime 2019-02-14T15:30:20+0800
	 */
	public function appList()
	{
        $code = session('code','');
        
        $where = '1=1';

        $count = db('district_app')->where($where)->count();

        $list = db('district_app')->alias('a')->join('ap_district b','a.district_id=b.id')->field('a.*,b.name as district_name')->where($where)->order('id desc')->paginate(10, false, [
            'query' => input()
        ]);

        return view('app_list',[
            'count'=> $count,
            'list'  =>  $list,
            'code'  =>  $code
        ]);
	}

	/**
	 * 修改代理申请
	 * @author 秋水
	 * @DateTime 2019-02-14T16:04:07+0800
	 */
	public function editApp()
	{
		if(request()->isPost()) {
			$id = input('id',0);
			$loginname = input('loginname', '');
			$password = input('password', '');
			$district_id = input('district_id', '');
			$reason = input('reason', '');
			$status = input('status', 1);

			$districtApp = db('district_app')->where('id',$id)->find();
			// 判断用户名是否重复
			$existDistrict = db('district')->where(['username'=>$districtApp['username']])->find();
			if($existDistrict) {
                Session::flash('code','err4');
                $this->redirect('district/editApp?id='.$id );
			}
			$existDistrict = db('district')->where(['username'=>$loginname])->find();
			if($existDistrict) {
                Session::flash('code','err5');
                $this->redirect('district/editApp?id='.$id );
			}
			if($status == 2) {
				// 通过
				if($loginname == '' || $password == '') {
	                Session::flash('code','err2');
	                $this->redirect('district/editApp?id='.$id );
				}

				$updateData = [
					'loginname' => $loginname,
					'password' => $password,
					'status' => $status,
					'update_time' => time()
				];

				$r = db('district_app')->where(['id'=>$id])->update($updateData);

				// 修改分区信息
				// $user = db('user')->where(['username'=>$districtApp['username']])->find();
				// if(!$user) {
	   //              Session::flash('code','err3');
	   //              $this->redirect('district/editApp?id='.$id );
				// }
				// $districtUpdateData = [
				// 	'user_id' => $user['id'],
				// 	'username' => $loginname,
				// 	'password' => md5($password)
				// ];

				// $r = db('district')->where(['id'=>$district_id])->update($districtUpdateData);
				if(!$r) {
					Session::flash('code','err1');
					$this->redirect('district/editApp?id='.$id );
				}
			} else if($status == 3) {
				// 拒绝
				if($reason == '') {
	                Session::flash('code','err2');
	                $this->redirect('district/editApp?id='.$id );
				}

				$updateData = [
					'reason' => $reason,
					'status' => $status
				];
			}

			$r = db('district_app')->where('id',$id)->update($updateData);
			if($r) {
				Session::flash('code','1');
                $this->redirect('district/appList');
            }else{
                Session::flash('code','err1');
                $this->redirect('district/editApp?id='.$id );
            };
		} else {
			$id = input('id', 0);
        	$code = session('code','');
			$data = db('district_app')->where('id',$id)->find();
			$district = db('district')->where('id',$data['district_id'])->find();

			if($data['status'] == 1) {
				// 等待审核
				$data['loginname'] = $data['username'];
				$data['password'] = rand(100000,999999);
			}

			$this->assign('district', $district);
			$this->assign('data',$data);
			$this->assign('code',$code);
			return view('edit_app');
		}
	}

	/**
	 * 删除申请
	 * @author 秋水
	 * @DateTime 2019-02-17T17:16:46+0800
	 */
	public function deleteApp()
	{
		$id = input('id', 0);

		$r = db('district_app')->where(['id'=>$id])->delete();

		if($r) {
			return json(['code'=>1,'msg'=>'删除成功']);
		} else {
			return json(['code'=>0,'msg'=>'删除失败']);
		}
	}

	/**
	 * 积分规则管理
	 * @author 秋水
	 * @DateTime 2019-02-16T10:25:49+0800
	 */
	public function pointRule()
	{
		if(request()->isPost()) {
			$minArr = input('min/a', []);
			$maxArr = input('max/a', []);
			$pointArr = input('point/a', []);
			$configData = db('todo_config')->where(['type'=>4,'title'=>'point_rule'])->find();

			$rule_data = [];
			foreach ($minArr as $key => $o) {
				$rule_data[] = ['min'=>$o,'max'=>$maxArr[$key],'point'=>$pointArr[$key]];
			}
			if(!$configData) {
				// 如果没有该数据，就添加一条
				$addData = [
					'type' => 4,
					'name' => '代理积分规则',
					'title' => 'point_rule',
					'value' => json_encode($rule_data)
				];

				db('todo_config')->insert($addData);
			} else {
				// 如果有该数据，就修改内容
				$updateData = ['value'=>json_encode($rule_data)];

				db('todo_config')->where(['id'=>$configData['id']])->update($updateData);
			}
            Session::flash('code','success');
			$this->redirect('pointRule');
		} else {
        	$code = session('code','');
			$configData = db('todo_config')->where(['type'=>4,'title'=>'point_rule'])->find();

			if($configData) {
				// 如果有数据，就返回对应值
				$ruleData = json_decode($configData['value'], true);
			} else {
				// 如果没有数据，就返回空值
				$ruleData = [];
			}

			$this->assign('code', $code);
			$this->assign('rule_data', $ruleData);
			return view('pointrule');
		}
	}

	/**
	 * 重置密码
	 * @author 秋水
	 * @DateTime 2019-02-21T15:20:00+0800
	 */
	public function resetPassword()
	{
		$password = input('password', '');
		$id = input('id', 0);

		if($password == '') {
			return json(['code'=>0,'msg'=>'密码不能为空']);
		}

		$updateData = ['password'=>$password];
		$r = db('district_app')->where('id',$id)->update($updateData);

		$districtUpdateData = ['password'=>md5($password)];
		$r = db('district')->where(['id'=>$id])->update($districtUpdateData);

		if($r !== false) {
			return json(['code'=>1, 'msg'=>'重置成功']);
		} else {
			return json(['code'=>0, 'msg'=>'重置失败']);
		}
	}
}